#include "serverthread.h"
#include "NetworkCommonFunction.h"

#include <QDebug>

ServerThread* ServerThread::createServerThread()
{
	static ServerThread* serverThread = new ServerThread;
	serverThread->start();
	return serverThread;
}

ServerThread::ServerThread(unsigned short port):
	m_Port(port)
{
}

void ServerThread::run()
{
	m_ServerSocket = socket(AF_INET, SOCK_STREAM, 0);
	if(m_ServerSocket == INVALID_SOCKET)
	{
		emit errorHappened(CreateSocketError);
		return;
	}

	int option = 1;
	int ret = setsockopt(m_ServerSocket, SOL_SOCKET, SO_REUSEADDR, (char*)&option, sizeof(option));
	if(ret == SOCKET_ERROR)
	{
		qDebug()<<"Set socket reuse address error";
	}

	SOCKADDR_IN serverSocketAddress;
	serverSocketAddress.sin_family = AF_INET;
	serverSocketAddress.sin_addr.s_addr = htonl(INADDR_ANY);
	serverSocketAddress.sin_port = htons(m_Port);

	if(bind(m_ServerSocket, (SA*)&serverSocketAddress, sizeof(serverSocketAddress)) == SOCKET_ERROR)
	{
		emit errorHappened(BindError);
		return;
	}

	if(listen(m_ServerSocket, SOMAXCONN) == SOCKET_ERROR)
	{
		emit errorHappened(ListenError);
		return;
	}

	while(true)
	{
		SOCKADDR_IN clientAddress;
		int clientAddressLen = sizeof(clientAddress);
		SOCKET clientSocket = accept(m_ServerSocket, (SA*)&clientAddress, &clientAddressLen);
		if(clientSocket == INVALID_SOCKET)
		{
			emit errorHappened(AcceptError);
			continue;
		}

		emit(newConnection(clientSocket));
		qDebug()<<"New connection:"<<inet_ntoa(clientAddress.sin_addr)<<":"<<ntohs(clientAddress.sin_port);
	}
}
